using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Xml.Serialization;
using TodoLister.Models;
using System.Windows;

namespace TodoLister.Services
{
    /// <summary>
    /// XML文件存储服务
    /// </summary>
    public class XmlFileStorageService : IFileStorageService
    {
        private readonly string _filePath;
        private readonly XmlSerializer _serializer;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="fileName">文件名</param>
        public XmlFileStorageService(string fileName)
        {
            // 使用AppData目录存储文件
            var appDataPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                "TodoLister"
            );
            
            // 确保目录存在
            if (!Directory.Exists(appDataPath))
            {
                Directory.CreateDirectory(appDataPath);
            }
            
            _filePath = Path.Combine(appDataPath, fileName);
            _serializer = new XmlSerializer(typeof(List<TodoItem>));
        }

        /// <summary>
        /// 保存待办事项列表
        /// </summary>
        /// <param name="items">待办事项列表</param>
        public async Task SaveItemsAsync(IEnumerable<TodoItem> items)
        {
            try
            {
                await Task.Run(() =>
                {
                    // 使用临时文件进行保存，避免写入过程中程序崩溃导致文件损坏
                    var tempFilePath = _filePath + ".tmp";
                    using (var writer = new StreamWriter(tempFilePath))
                    {
                        _serializer.Serialize(writer, new List<TodoItem>(items));
                    }
                    
                    // 如果保存成功，将临时文件重命名为正式文件
                    if (File.Exists(_filePath))
                    {
                        File.Delete(_filePath);
                    }
                    File.Move(tempFilePath, _filePath);
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存待办事项列表失败：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
                throw;
            }
        }

        /// <summary>
        /// 加载待办事项列表
        /// </summary>
        /// <returns>待办事项列表</returns>
        public async Task<IEnumerable<TodoItem>> LoadItemsAsync()
        {
            try
            {
                if (!File.Exists(_filePath))
                {
                    return new List<TodoItem>();
                }

                return await Task.Run(() =>
                {
                    using (var reader = new StreamReader(_filePath))
                    {
                        return (List<TodoItem>)_serializer.Deserialize(reader);
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载待办事项列表失败：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return new List<TodoItem>();
            }
        }
    }
} 
